// pages/user/order-info/order-info.js
let app = getApp();
const moment = require('../../../utils/moment.min.js');
import Dialog from '../../../miniprogram/miniprogram_npm/vant-weapp/dialog/dialog'
import Toast from '../../../miniprogram/miniprogram_npm/vant-weapp/toast/toast'
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
var qqmapsdk = new QQMapWX({
  key: 'SUPBZ-LDKCG-EWLQI-IS2I5-WQU3T-OGF36' // 必填
});
const STATUS_TEXT = {
  '-1': "已取消",
  0: "待付款",
  1: "待发货",
  2: "已发货",
  25: "部分发货",
  3: "已收货",
  4: "待退款",
  5: "售后中",
  6: "已完成",
  7: "商家已接单",
}
const ASSEMBLE_TEXT = {
  1: "拼团中",
  2: "拼团成功",
  3: "拼团失败",
  4: "取消拼团",
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: '',
    shop: '',
    ASSEMBLE_TEXT,
    payId: '',
    thenId: '',
    iskuaidi: '',// 1快递直发
    serverTime: null,
    order: null,
    goods_express: [],
    goods_nextDay: [],
    balance: null,//余额
    points: null,//可用积分
    usePoints: false,//是否使用积分
    avatarImg: [],//其它购买伙伴头像
    productCount: null,//商品总数
    payPrice: null,//实付金额
    deductPrice: null,//积分抵扣
    pointsTransform: null,//积分配置
    isSubmit: false,//是否开启加载
    payTime: null,//剩余支付时间
    payTimeData: {},
    statusText: null,//订单状态
    payRadio: 'wx',//支付方式
    balanceDisable: false,//是否禁用勾选余额支付
    isRechargeCard: false,//充值卡弹框
    rechargeCardList: [],//可用充值卡
    rechargeCardId: -1,//充值卡id
    flag: '',
    sendRadio: '1', //配送方式

    latitude: 28.224638,
    longitude: 112.98822,
    markers: [],
    polyline: [],
    points: [],
    qishouInfo:{},//骑手信息
    // covers: [{
    //   latitude: 28.224638,
    //   longitude: 112.98822,
    //   iconPath: 'https://o.rjkj7.com/data/upload/xcximages/is_empty.png',
    // }, {
    //   latitude: 28.219710854,
    //   longitude: 112.988020427,
    //   iconPath: 'https://o.rjkj7.com/data/upload/xcximages/is_empty.png',
    //   title:11,
    // }]
  },
  onReady: function (e) {
    this.mapCtx = wx.createMapContext('myMap')
  },

  getOrder() {
    let _this = this;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/order',
      data: {
        orderId: _this.data.payId,
        id: _this.data.thenId,
        iskuaidi: _this.data.iskuaidi,
        shopId: _this.data.shop.id,
        Authorization: wx.getStorageSync('authToken'),
        number: Math.random()
      },
      load: 0
    }).then((res) => {
      _this.data.serverTime = res.data.time;
      _this.data.order = res.data.data;

      if (wx.getStorageSync('globalConfig') == '') app.setGlobalConfig(_this.data.order.centreId);
      _this.data.sendRadio = _this.data.order.dispatchtype == 0 ? '0' : '1';
      _this.data.shop = res.data.shop || _this.data.shop;
      _this.data.order.shopName = _this.data.shop.realname || ''
      _this.data.order.shopMobile = _this.data.shop.mobile || ''
      _this.data.order.shopXiaoqu = _this.data.shop.tXiaoqu || ''
      _this.data.order.shopAddress = _this.data.shop.tProvince + _this.data.shop.tCity + _this.data.shop.tArea
        + _this.data.shop.tXiaoqu + _this.data.shop.tShopname;

      _this.data.balance = res.data.balance || '';
      _this.data.points = res.data.points || '';

      _this.onDifferentiate(_this.data.order.orderProducts);
      _this.headImg();

      _this.setData({
        order: _this.data.order,
        balance: _this.data.balance,
        points: _this.data.points,
        sendRadio: _this.data.sendRadio
      })


      _this.productCountFun()
      _this.payPriceFun()
      _this.pointsTransformFun()
      _this.deductPriceFun()
      _this.payTimeFun()
      _this.statusTextFun()
      _this.balanceDisableFun()
      if ((_this.data.order.status == 7 || _this.data.order.status == 8 || _this.data.order.status == 9) && (_this.data.order.deliveryStatus == 5 || _this.data.order.deliveryStatus == 6 || _this.data.order.deliveryStatus == 7)) {
        _this.getPosition()
      }
    })
  },

  //获取充值卡
  getRechargeCard() {
    let _this = this
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/shipcard/getShipcardByMid',
      data: {
        mid: _this.data.user.id,
        centreId: _this.data.user.centreId,
        price: _this.data.payPrice,
      },
      load: 1
    }).then((res) => {
      _this.setData({ rechargeCardList: res.data.data })
    })
  },

  //区分数据，团购/快递
  onDifferentiate(i) {
    let _this = this;
    _this.setData({
      goods_express: [],
      goods_nextDay: [],
    })
    i.forEach((goods, i) => {
      goods.picArr = [];
      goods.prodlabels.split(",").forEach(item => {
        if (item) goods.picArr.push(item);
      })
      if (goods.isKuaidi) {
        _this.data.goods_express.push(goods);
      } else {
        _this.data.goods_nextDay.push(goods);
      }
    });
    _this.setData({
      goods_express: _this.data.goods_express,
      goods_nextDay: _this.data.goods_nextDay,
    })
  },
  //还有其它伙伴购买了
  headImg() {
    let _this = this;
    app.requestUrl({
      method: 'POST',
      url: '/wxapi/getOrderUserHeadImg',
      data: {
        productId: _this.data.order.orderProducts[0].productId,
        limit: 7,
        offset: 0,
      },
      load: 0
    }).then((res) => {
      _this.setData({
        avatarImg: res.data.data.rows
      })
    })
  },

  //商品总数
  productCountFun() {
    let _this = this;
    let total = 0;
    _this.data.order.orderProducts.forEach(item => {
      total += item.total
      _this.setData({
        productCount: total
      })
    })
  },
  //实付金额
  payPriceFun() {
    let _this = this;
    let temp = null;
    if (_this.data.order.status === 0) {
      temp = Math.max(_this.data.order.orderprice + _this.data.order.dispatchprice - _this.data.order.discountprice - _this.data.deductPrice, 0);
    } else {
      temp = _this.data.order.payprice + _this.data.order.dispatchprice;
    }
    _this.setData({
      payPrice: temp
    })

    _this.getRechargeCard()//充值卡接口
  },
  //积分抵扣
  deductPriceFun() {
    let _this = this
    let temp = null
    if (_this.data.order.status === 0) {
      if (_this.data.usePoints) {//使用积分
        temp = Math.min(_this.data.order.orderprice - _this.data.order.discountprice, _this.data.points / _this.data.pointsTransform)
        _this.setData({ deductPrice: temp })
        return
      }
      temp = 0
      _this.setData({ deductPrice: temp })
    }
    else {
      temp = _this.data.order.deductprice
      _this.setData({ deductPrice: temp })
    }
  },
  //积分抵扣配置
  pointsTransformFun() {
    let _this = this;
    let config = JSON.parse(wx.getStorageSync('globalConfig'));
    let transform = config ? (config.exchangeIntegral || 100) : 100;
    _this.setData({
      pointsTransform: transform
    })
  },
  //倒计时初始值
  payTimeFun() {
    let _this = this;
    let config = JSON.parse(wx.getStorageSync('globalConfig'));
    let createTime = moment(_this.data.order.createTime).unix() * 1000;
    let payTime = config ? config.autoCloseNoPayOrderMin : 5;
    let left = (payTime || 5) * 60 * 1000 - (_this.data.serverTime - createTime);
    _this.setData({
      payTime: (left > 0) ? left : 0
    })
  },

  //支付倒计时监听改变
  payTimeChange(e) {
    this.setData({
      payTimeData: e.detail
    });
    this.statusTextFun();
  },
  //支付倒计时结束
  payTimeFinish() {
    this.setData({
      'order.status': -1
    })
  },

  //状态
  statusTextFun() {
    let _this = this;
    const status = _this.data.order.status;
    _this.setData({
      statusText: STATUS_TEXT[status]
    })
  },
  //校验余额
  balanceDisableFun() {
    let _this = this;
    _this.setData({
      balanceDisable: _this.data.balance < _this.data.payPrice,
      payRadio: _this.data.rechargeCardId != -1 ? 'card' : _this.data.balance < _this.data.payPrice ? 'wx' : 'yu'
    })
  },

  //选择支付方式
  radioChange(event) {
    if (event.detail != 'card')
      this.setData({ rechargeCardId: -1 })

    this.setData({
      payRadio: event.detail
    });
  },

  //使用积分
  pointsChange(event) {
    this.setData({ usePoints: event.detail })
    this.deductPriceFun();
    this.payPriceFun();
  },

  //打开充值卡
  isRechargeCardClick() {
    let _this = this
    if (_this.data.rechargeCardList.length == 0) return
    this.setData({
      isRechargeCard: true,
      rechargeCardId: _this.data.rechargeCardId == -1 ? -1 : _this.data.rechargeCardList[0].id,//默认选择第一张充值卡
    })
  },
  //充值卡选择
  rechargeCardChange(event) {
    let _this = this
    _this.setData({
      rechargeCardId: event.detail
    })
  },
  //不使用优惠卷，-1不使用优惠卷
  onCancelRechargeCard() {
    this.setData({
      isRechargeCard: false,
      rechargeCardId: -1
    })
    this.balanceDisableFun()
  },
  //使用充值卡
  onSubmitRechargeCard() {
    let _this = this
    this.setData({
      isRechargeCard: false,
      rechargeCardId: _this.data.rechargeCardId == -1 ? -1 : _this.data.rechargeCardId,
    })
    if (_this.data.rechargeCardId != -1)
      _this.balanceDisableFun()

  },

  //取消订单
  cancelOrder() {
    let _this = this;

    if (_this.data.order.status === 1) { //订单已支付
      let cancelAble = true;
      for (let goodsIndex = 0; goodsIndex < _this.data.order.orderProducts.length; ++goodsIndex) {
        if (_this.data.order.orderProducts[goodsIndex].uncancelable === 1) {//订单里存在不支持无理由退单
          cancelAble = false;
          break;
        }
      };
      if (!cancelAble) {
        Dialog.alert({
          message: '有不支持无理由退单商品，无法取消订单'
        });
        return;
      }
    }

    Dialog.confirm({
      message: '确定要取消该订单吗？',
    }).then(() => {
      app.requestUrl({
        method: 'POST',
        url: '/wxapi/order/cancel',
        data: {
          orderId: _this.data.order.id,
        }
      }).then((res) => {
        _this.data.order.status = -1;
        _this.data.order.orderProducts.forEach(goods => {
          goods.status = -1;
        });
        _this.setData({
          'order.orderProducts': _this.data.order.orderProducts,
          'order.status': _this.data.order.status,
        })
        this.statusTextFun();
        Toast.success('已取消该订单');
      })
    }).catch(() => { })

  },
  //去支付
  onPayment() {
    let _this = this
    let user = app.getUser()
    let points = _this.data.usePoints ? Math.abs(Math.round(_this.data.deductPrice * _this.data.pointsTransform)) : '';

    //余额支付
    if (_this.data.payRadio == 'yu' || _this.data.payPrice == 0 || _this.data.payRadio == 'card') {
      Dialog.confirm({
        message: "余额支付：¥" + _this.data.payPrice.toFixed(2),
      }).then(() => {
        app.requestUrl({
          method: 'POST',
          url: '/wxapi/order/yupay',
          data: {
            orderId: _this.data.payId,
            shipcardRecordId: _this.data.rechargeCardId != -1 ? _this.data.rechargeCardId : '',//充值卡id
            couponId: _this.data.order.trId,//优惠卷id
            points: points//积分抵扣
          },
          load: 1
        }).then((res) => {
          wx.reLaunch({
            url: '/sub/user/payResult/payResult?status=success&id=' + _this.data.payId
          })
        })
      }).catch(() => {
        wx.reLaunch({
          url: '/sub/user/payResult/payResult?status=fail&id=' + _this.data.payId
        })
      })
    }
    //微信支付
    else if (_this.data.payRadio == 'wx') {
      if (!user.appOpenid) {//支付授权
        wx.navigateTo({
          url: '/pages/login-pay/login-pay'
        })
      } else {
        app.requestUrl({
          method: 'POST',
          url: '/wxapi/order/apppay',
          data: {
            orderId: _this.data.payId,
            couponId: _this.data.order.trId,//优惠卷id
            points: points//积分抵扣
          }
        }).then((res) => {
          let party = {};
          let respData = res.data.data.respData;
          if (respData) {
            party.addId = respData.payAppId;
            party.nonceStr = respData.paynonceStr;
            party.package = respData.payPackage;
            party.paySign = respData.paySign;
            party.signType = respData.paySignType;
            party.timeStamp = respData.payTimeStamp;
          }
          //兼容微信支付，第三方支付
          let last = respData ? party : res.data.data;
          //发起微信支付
          wx.requestPayment({
            ...last,
            success(res) {
              wx.reLaunch({
                url: '/sub/user/payResult/payResult?status=success&id=' + _this.data.payId
              })
            },
            fail(res) {
              wx.reLaunch({
                url: '/sub/user/payResult/payResult?status=fail&id=' + _this.data.payId
              })
            }
          })
        })
      }

    }
  },

  //查看物流
  toLogistics(event) {
    let index = event.currentTarget.dataset.index
    let kuaidisn = this.data.order.orderProducts[index].kuaidisn
    let expressCode = this.data.order.orderProducts[index].expressCode;
    wx.navigateTo({
      url: '/sub/user/logistics/logistics?kuaidisn=' + kuaidisn + '&expressCode=' + expressCode
    })
  },
  tocomment(e) {
    wx.setStorageSync('orderInfo', this.data.order);
    wx.navigateTo({
      url: '/sub/user/comments/comments',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (event) {
    let _this = this;
    _this.setData({
      payId: event.payId,
      thenId: event.id || '',
      iskuaidi: event.iskuaidi || '',
      flag: event.flag || '',
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this;
    _this.setData({
      shop: app.getShop(),
      user: app.getUser(),
    })
    _this.getOrder();
  },
  // 获取经纬度
  getPosition() {
    console.log(1);
    let _this = this;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/shop/candao/getRiderPosition',
      data: {
        orderId: _this.data.payId,
      },
      load: 0
    }).then((res) => {
      let qishouInfo = res.data.data;
      _this.setData({
        qishouInfo:qishouInfo,
      })
      // 用户经纬度
      let userLng = _this.data.user.lng;
      let userLat = _this.data.user.lat;
      //商家经纬度
      let shopLng = _this.data.shop.tLng;
      let shopLat = _this.data.shop.tLat;
      console.log(userLng+'--'+userLat);
      console.log(shopLng+'--'+shopLat);
      console.log(qishouInfo.longitude+'--'+qishouInfo.latitude);
      console.log(_this.data.shop);
      var start = '';
      var end = '';
      // 如果order接口里面的deliveryStatus等于5或者6，则是骑手到商家的距离，其他的状态则是骑手到用户的距离
      if(_this.data.order.deliveryStatus == 5 || _this.data.order.deliveryStatus == 6){
        start = qishouInfo.latitude + "," + qishouInfo.longitude;
        end = shopLat + "," + shopLng;
      }else{
        start = qishouInfo.latitude + "," + qishouInfo.longitude;
        end = userLat + "," + userLng;
      };
      // start = "28.19635" + "," + '112.97733';
      // end = "28.219710854" + "," + "112.988020427";
      _this.line(start, end);
      _this.getMarkers();
    })
  },
  line: function (start, end) {
    var _this = this
    qqmapsdk.direction({
      mode: 'bicycling',//可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
      from: start,
      to: end,
      success: function (res, data) {
        var ret = res;
        var coors = ret.result.routes[0].polyline, pl = [];
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        var kr = 1000000;
        for (var i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
        }
        //将解压后的坐标放入点串数组pl中
        for (var i = 0; i < coors.length; i += 2) {
          pl.push({ latitude: coors[i], longitude: coors[i + 1] })
        }
        //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
        _this.setData({
          latitude: pl[0].latitude,
          longitude: pl[0].longitude,
          polyline: [{
            points: pl,
            color: "#37C4FF",
            width: 4,
            dottedLine: false
          }]
        })
      },
      fail: function (error) {
        // console.error(error);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },
  getMarkers() {
    let _this = this;
    // 用户经纬度
    let userLng = _this.data.user.lng;
    let userLat = _this.data.user.lat;
    //商家经纬度
    let shopLng = _this.data.shop.tLng;
    let shopLat = _this.data.shop.tLat;
    // 骑手经纬度
    let qishouInfo = _this.data.qishouInfo;
    // 骑手状态
    let qishouContent = '';
    let distance = qishouInfo.distance;
    if(distance >= 1000){
      distance = (distance / 1000).toFixed(2) + 'km';
    }else{
      distance = distance + 'm';
    };
    if((_this.data.order.status == 7 || _this.data.order.status == 8 || _this.data.order.status == 9) && _this.data.order.deliveryStatus==5){
      qishouContent = '骑手正赶往商家，距离商家还有' + distance;
    };
    if((_this.data.order.status == 7 || _this.data.order.status == 8 || _this.data.order.status == 9) && _this.data.order.deliveryStatus==6){
      qishouContent = '骑手已到店';
    }
    if((_this.data.order.status == 7 || _this.data.order.status == 8 || _this.data.order.status == 9) && _this.data.order.deliveryStatus==7){
      qishouContent = "    骑手配送中    \n    还有" + distance;
      
    };
    var markers = [{
      id: 1,
      latitude: userLat,
      longitude: userLng,
      name: '用户',
      iconPath: this.data.user.avatar,
      width: '70rpx',
      height: '70rpx',
      callout: {
        content: '',
        color: '#f50',
        display: 'ALWAYS',
        anchorY: '-20',
      },
      zIndex:2,
    }, {
      id: 2,
      latitude: shopLat,
      longitude: shopLng,
      name: '店铺',
      iconPath: _this.data.shop.store ? _this.data.shop.store : 'https://o.rjkj7.com/data/upload/xcximages/nostore.png',
      width: '70rpx',
      height: '70rpx',
      callout: {
        content: '',
        color: '#f50',
        display: 'ALWAYS',
        anchorY: '-20',
      },
      zIndex:2,
    }, {
      id: 3,
      latitude: qishouInfo.latitude,
      longitude: qishouInfo.longitude,
      name: '骑手',
      iconPath: 'https://o.rjkj7.com/data/upload/xcximages/canyin_1.png',
      width: '70rpx',
      height: '60rpx',
      callout: {
        content: qishouContent,
        color: '#FF0000',
        display: 'ALWAYS',
        anchorY: '-20',
        borderRadius:'10rpx',
        padding:'6rpx 6rpx 6rpx 0',
      },
      zIndex:9999,
    }];
    let startlatitude = '';
    let startlongitude = '';
    let endlatitude = '';
    let endlongitude = '';
    startlatitude = qishouInfo.latitude;
    startlongitude = qishouInfo.longitude;
    // 如果order接口里面的deliveryStatus等于5或者6，则是骑手到商家的距离，其他的状态则是骑手到用户的距离
    if(_this.data.order.deliveryStatus == 5 || _this.data.order.deliveryStatus == 6){
      endlatitude = shopLat;
      endlongitude = shopLng;
    }else{
      endlatitude = userLat;
      endlongitude = userLng;
    }
    var points_ = [
      {
        latitude: startlatitude,
        longitude: startlongitude,
      },
      {
        latitude: endlatitude,
        longitude: endlongitude,
      }
    ];
    _this.setData({
      markers: markers,
      points: points_
    })
  },
  // 刷新
  refresh(){
    this.getOrder();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
